Ext.namespace("Dudley");
Ext.namespace("Dudley.lims");

Dudley.lims.DeletionOligo = function() {

    var myDOData = [];
    var doligoForm = {};
    var doligoPanel = {};
    var doligoHash = null;
    var doligoCount = null;
    var doligoMaxNum = null;
    var doligoStore = null;
    var doligoLoaded = false;
    var pagingBar = null;
    var updateAlert = null;
    var searchInput = 'DO';
    var searchOption = 'doligoFields';
    var spotlightMenu = sptlght.utils.SpotlightUtils.getSpotlightMenu("dospotlightmenuid");

    function initDOStore(failedCb, callback) {
        loadDOSearchResult(0, null, callback);
    }

    function loadDOSearchResult(index, searchResultJSON, callback) {
        doligoStore = loadSolrSearchResult("DO", getOligoPagingColumns(), oligoSolrTranslator, index, searchResultJSON);
        doligoStore.load({params:{start:0, limit:10}}, callback());		     
    }

    function goSearch(index, doligoSearchInput, doligoSearchOption) {
        if (doligoSearchInput == '') {
                doligoSearchInput = 'DO';
        }
        doligoSearchInput = checkWildcard(doligoSearchInput);
        var searchUrl = getSolrSearchUrl(getLuceneTerm(doligoSearchOption, doligoSearchInput), 1000, "doligoKey,doligoName,doligoNotes,doligoGene,doligoSequence,doligoYName,doligoProject,doligoModification,doligoPurification,doligoConcentration,doligoOrderedBy,doligoComments");
        var searchWin = getSearchLoadingWindow("deletionoligo-");
        searchWin.on("show", function () {
            var sb = Ext.getCmp("deletionoligo-search-statusbar");
            sb.showBusy();
        });        
        searchWin.show();
        Ext.Ajax.request({
            url: searchUrl,
            method: "GET",
            success: function(response) {
                var searchResultObj = Ext.util.JSON.decode(response.responseText);
                console.log("DOligo Result count:" + searchResultObj.response.numFound);                
                loadDOSearchResult(index, searchResultObj.response, function() {
                    Ext.getDom("sample-search-result-list").innerHTML = "";
                    Ext.getDom("yo-form").innerHTML = "";
                    searchWin.close();
                    renderDOSearchResult();
                });
            },
            failure: function() {
                eventManager.fireStatusMessageEvent({ text: "Search Results failed for url:" + searchUrl, level: "error" });
            }
        });
    }

    function loadDOPanel() {
       var doligoSearchForm = getSearchForm("doligoSearchButtonId", "doligoSearchInputId", null);
       Ext.getCmp("doligoSearchButtonId").addListener("click", function(){
			goSearch(0, Ext.getCmp("doligoSearchInputId").getValue(), "doligoFields");		
	   });		
       var tbarButtons = [
            {
                id: 'showDOSearchResultsId',
                name: 'showDOSearchResults',
                disabled: true,
                text: '<--Search Results',
                icon: "images/back-green.png",
                cls:'x-btn-text-icon',
                listeners: {click:
                        function() {
                            Ext.getDom("yo-form").innerHTML = "";
                            renderDOSearchResult();
                        }
                }
            },
            {
                id: 'searchAllDOId',
                name: 'searchAllDO',
                disabled: false,
                text: 'View All Records',
                icon: "images/search-blue.png",
                cls:'x-btn-text-icon',
                listeners: {click:
                        function() {
                            Ext.getDom("yo-form").innerHTML = "";
                            goSearch(0, 'DO', 'doligoKey');
                        }
                }
            },
            {
                id: 'createNewDOId',
                name: 'createNewDO',
                text: 'Create New DO',
                icon: "images/add-green.png",
                cls:'x-btn-text-icon',
                listeners: {click:
                        function() {
                            Dudley.lims.DeletionOligo.loadNewDO();
                        }
                }
            }
        ];
        doligoPanel = new Ext.Panel({
            id: "doligoPanelId",
            autoHeight: true,
            border: true,
            renderTo: "yad-panel",
            title: "Deletion Oligo",
            header: false,
            tbar: tbarButtons,
            items: doligoSearchForm
        });
        doligoPanel.on("activate", function () {
            Ext.getDom("yo-panel").innerHTML = "";
            Ext.getDom("yo-form").innerHTML = "";
            Ext.getDom("sample-search-result-list").innerHTML = "";
            if (doligoLoaded == false) {
                doligoLoaded = true;
                goSearch(0, 'DO', 'doligoKey');
            }
            renderDOSearchResult();
        });
    }

    function postDOStrain(createNew) {
        var oligoKey = Ext.getCmp("doligoKeyId").getValue();
        var oligoName = Ext.getCmp("doligoNameId").getValue();
        var doPostJson = new Object();
        doPostJson["doligoName"] = oligoName;
        doPostJson["doligoYName"] = Ext.getCmp("doligoYNameId").getValue();
        doPostJson["doligoKey"] = oligoKey;
        doPostJson["doligoNotes"] = Ext.getCmp("doligoNotesId").getValue();
        doPostJson["doligoSequence"] = Ext.getCmp("doligoSequenceId").getValue();
        doPostJson["doligoGene"] = Ext.getCmp("doligoGeneId").getValue();
        doPostJson["doligoProject"] = Ext.getCmp("doligoProjectId").getValue();
        doPostJson["doligoModification"] = Ext.getCmp("doligoModificationId").getValue();
        doPostJson["doligoPurification"] = Ext.getCmp("doligoPurificationId").getValue();
        doPostJson["doligoConcentration"] = Ext.getCmp("doligoConcentrationId").getValue();
        doPostJson["doligoComments"] = Ext.getCmp("doligoCommentsId").getValue();
        var delOligoCallback = function() {
            limsadmin_obj["limsadminDOligoCount"] = doligoCount; 
            limsadmin_obj['limsadminDOligoMaxNum'] = doligoMaxNum;
            postSolrUpdates(limsadmin_obj, function(){
                eventManager.fireStatusMessageEvent({ text: "New DeletionOligo Added Successfully", level: "info" });
                Ext.Msg.alert('Info', "New DeletionOligo " + oligoKey + ' Added Successfully');
                Ext.getDom("yo-form").innerHTML = "";
                Ext.getDom("sample-search-result-list").innerHTML = "";
                goSearch(0, oligoKey, "doligoKey");
            });
        };
        if (!createNew) {
            delOligoCallback = function() {
                Ext.Msg.alert('Info', oligoKey + ' Updated Successfully');
                Ext.getDom("sample-search-result-list").innerHTML = "";
                var searchResultsButton = Ext.getCmp("showDOSearchResultsId");
                searchResultsButton.disable();
            };
        }
        postSolrUpdates(doPostJson, delOligoCallback);
    }

    function doYGeneRefresh() {
        var yname = Ext.getCmp("doligoYNameId").getValue();
        if (yname == "") {
            alert("YName is required");
            return;
        }
        var nameposition = Ext.getCmp("doligoNameId").getValue();
        var npsplitted = nameposition.split("_");
        if (npsplitted.length == 2) {
            var position = npsplitted[1];
            if (position.length != 1) {
                Ext.Msg.alert("Primer Position must be A, B, C, or D");
            } else {
                resolveBandSizeAndSequence(yname, position.toLowerCase());
            }
        } else {
            Ext.Msg.alert("Oligo Name_Position is required and must be in form of GENE_X, where X is A, B, C, or D");
        }
    }

    function updateYGeneLookup(seq, bandsizes) {
        Ext.getCmp("doligoSequenceId").setValue(seq);
        Ext.getCmp("doligoNotesId").setValue(bandsizes);
        var oligoKey = Ext.getCmp("doligoKeyId").getValue();
        var doPostJson = new Object();
        doPostJson["notes"] = bandsizes;
        doPostJson["sequence"] = seq;
        var delOligoUrl = "/addama-rest/dudley-sample/path/datasource/DO/" + oligoKey + "/annotations";
        postDudleyAnnotations(delOligoUrl, doPostJson, function() {
            Ext.Msg.alert("Deletion oligo updated");
            updateAlert.close();
        });
    }

    function resolveBandSizeAndSequence(ygenename, primer_position) {
        var primerseq = primer_position + "_seq";
        //http://localhost:8080/google-dsapi-svc/addama/datasources/omics/omics_samples/query?tq=select%20*%20
        // where%20strains%20contains%20%27YO_300%27%20or%20strains%20contains%20%27YO_502%27&tqx=out:html
        // /query?tq=select%20*%20where%20sample_key%20=%20%27YO_8%27&tqx=out:html
        var querySql = "select orf_name, " + primerseq + ", a_d_del, a_kanb, d_kanc, a_d_wt, ab_wt, cd_wt where orf_name = '" + ygenename + "'";
        var query = new google.visualization.Query("/google-dsapi-svc/addama/datasources/omics/deletion_primer_pcr/query?tq=" + querySql);
        query.send(function(response) {
            if (response.isError()) {
                Ext.Msg.alert("warning", "error at retrieving deletion primer pcr data for yname:" + ygenename + "<br>" + response.getMessage());
                return;
            }
            var pcrdata = response.getDataTable();
            if (pcrdata.getNumberOfRows() >= 1) {
                var pcrarray = vq.utils.GoogleDSUtils.dataTableToArray(pcrdata);
                if (pcrdata.getNumberOfRows() != 1) {
                    var pcrinfo = "";
                    for (var i = 0; i < pcrarray.length; i++) {
                        var bandsizes = pcrarray[i]["a_d_del"] + " " + pcrarray[i]["a_kanb"] + " "
                                + pcrarray[i]["d_kanc"] + " " + pcrarray[i]["a_d_wt"] + " " + pcrarray[i]["ab_wt"] + " " + pcrarray[i]["cd_wt"];
                        var ygeneLink = '<br><A HREF="javascript:Dudley.lims.DeletionOligo.selectYGene(\'' + pcrarray[i][primerseq] + '\', \'' + bandsizes + '\')">' + pcrarray[i]["orf_name"] + '</A>';
                        pcrinfo = pcrinfo + ygeneLink + " " + bandsizes +
                                  " " + pcrarray[i][primerseq] + "<br><br>";
                    }
                    updateAlert = new Ext.Window({
                        title: 'Select Sequence and Bandsizes',
                        width: 200,
                        height: 300,
                        autoScroll: true,
                        modal: true,
                        bodyStyle: 'padding:2px;',
                        html: ygenename + " has duplicate sequences/bandsizes in the database, please curate by selecting the YGene link below:<br>" + pcrinfo,
                        layout: 'fit'
                    });
                    updateAlert.show();
                } else {
                    Ext.getCmp("doligoNotesId").setValue(pcrarray[0]["a_d_del"] + " " + pcrarray[0]["a_kanb"] + " "
                            + pcrarray[0]["d_kanc"] + " " + pcrarray[0]["a_d_wt"] + " " + pcrarray[0]["ab_wt"] + " " + pcrarray[0]["cd_wt"]);
                    Ext.getCmp("doligoSequenceId").setValue(pcrarray[0][primerseq]);
                }
            } else {
                Ext.Msg.alert("info", "No primer pcr data exists for ygenename:" + ygenename);
            }
        });
    }

    function loadCreateDOStrain(doligoHash, callback) {
        var primerLinks = "";
        var yrefreshLink = '';
        var createNew = true;
        var buttons = [
            {
                id: 'createButton',
                name: 'createButton',
                text: 'Create',
                listeners: {click:
                        function() {
                            if (validateCreateUpdateOligo('DO')) {
                                postDOStrain(createNew);
                            }
                        }
                }
            }
        ];
        if (doligoHash != null) {
            var primerName = doligoHash.oligoName;
            var splittedPrimer = primerName.split("_");
            var genePrimer = splittedPrimer[0];
            if (primerName.indexOf("_A") != -1) {
                primerLinks = '<A HREF="javascript:Dudley.lims.DeletionOligo.viewPrimer(\'B\')">' + genePrimer + '_B</A>&nbsp;'
                        + '<A HREF="javascript:Dudley.lims.DeletionOligo.viewPrimer(\'C\')">' + genePrimer + '_C</A>&nbsp;'
                        + '<A HREF="javascript:Dudley.lims.DeletionOligo.viewPrimer(\'D\')">' + genePrimer + '_D</A>&nbsp;';
            } else if (primerName.indexOf("_B") != -1) {
                primerLinks = '<A HREF="javascript:Dudley.lims.DeletionOligo.viewPrimer(\'A\')">' + genePrimer + '_A</A>&nbsp;'
                        + '<A HREF="javascript:Dudley.lims.DeletionOligo.viewPrimer(\'C\')">' + genePrimer + '_C</A>&nbsp;'
                        + '<A HREF="javascript:Dudley.lims.DeletionOligo.viewPrimer(\'D\')">' + genePrimer + '_D</A>&nbsp;';
            } else if (primerName.indexOf("_C") != -1) {
                primerLinks = '<A HREF="javascript:Dudley.lims.DeletionOligo.viewPrimer(\'A\')">' + genePrimer + '_A</A>&nbsp;'
                        + '<A HREF="javascript:Dudley.lims.DeletionOligo.viewPrimer(\'B\')">' + genePrimer + '_B</A>&nbsp;'
                        + '<A HREF="javascript:Dudley.lims.DeletionOligo.viewPrimer(\'D\')">' + genePrimer + '_D</A>&nbsp;';
            } else if (primerName.indexOf("_D") != -1) {
                primerLinks = '<A HREF="javascript:Dudley.lims.DeletionOligo.viewPrimer(\'A\')">' + genePrimer + '_A</A>&nbsp;'
                        + '<A HREF="javascript:Dudley.lims.DeletionOligo.viewPrimer(\'B\')">' + genePrimer + '_B</A>&nbsp;'
                        + '<A HREF="javascript:Dudley.lims.DeletionOligo.viewPrimer(\'C\')">' + genePrimer + '_C</A>&nbsp;';
            }
            yrefreshLink = '<br><A HREF="javascript:Dudley.lims.DeletionOligo.refreshYGene()">Refresh</A>';
            if (doligoHash.genotype != undefined && doligoHash.genotype == 'Record Deleted') {
                buttons = [];
            } else {
                buttons = [
                    {
                        id: 'updateDOButtonId',
                        name: 'updateDOButton',
                        text: 'Update',
                        listeners: {click:
                                function() {
                                    if (validateCreateUpdateOligo('DO')) {
                                        postDOStrain(!createNew);
                                    }
                                }
                        }
                    }
                ];
            }
        } else {
            doligoHash = new Object();
            var doligoMaxInt = parseInt(doligoMaxNum);
            doligoMaxInt = doligoMaxInt + 1;
            var doligoCountInt = parseInt(doligoCount);
            doligoCountInt = doligoCountInt + 1;
            doligoCount = doligoCountInt + "";
            doligoHash.name = 'DO' + doligoMaxInt;
            doligoMaxNum = doligoMaxInt + "";
        }
        var notesArray = null;
        var label_title = new Ext.form.Label({});
        var label_top = new Ext.form.Label({});
        var label_image = new Ext.form.Label({});
        var label_bottom = new Ext.form.Label({});

        if (doligoHash.notes != null) {
            notesArray = doligoHash.notes.split(" ");

            label_title = new Ext.form.Label({
                id:"imageLabel1Id",
                //fieldLabel: "Image",
                html: "<b>Oligo Primer Design<br>" + doligoHash.oligoName + "&nbsp;" + primerLinks
                        + "<br>                                                                    "
                        + doligoHash.sequence + "</b><br>",
                width: 500
            });
            label_top = new Ext.form.Label({id:"imageLabel4Id",
                //fieldLabel: "&nbsp;&nbsp;",
                html: "<font color='red'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;A_D_Deletion-" + notesArray[0]
                        + "bp</font> or <font color='blue'> A_D_WildType-" + notesArray[3] + "bp</font>&nbsp;&nbsp;&nbsp<br></font>",
                width: 500
            });
            label_image = new Ext.form.Label({
                id:"imageLabel2Id",
                //fieldLabel: "&nbsp;&nbsp;",
                html: "&nbsp;&nbsp;<img src='images/deletionOligoBase.png' title='DeletionOligoBase'>",
                width: 500
            });
            label_bottom = new Ext.form.Label({id:"imageLabel3Id",
                //fieldLabel: "&nbsp;&nbsp;",
                html: "<font color='red'><br>A_KANB_Deletion-" + notesArray[1] + "bp</font> or <font color='blue'>AB_WildType-"
                        + notesArray[4] + "bp</font>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<font color='red'>D_KANC_Deletion- " + notesArray[2]
                        + "bp</font> or <font color='blue'>CD_WildType-" + notesArray[5] + "bp</font>",
                width: 500
            });
        }

        doligoForm = new Ext.form.FormPanel({
            id: 'doligoForm',
            method: 'POST',
            autoHeight: true,
            autoScroll: true,
            border: true,
            buttonAlign: 'left',
            buttons: buttons,
            items: [
                new Ext.form.FieldSet({
                    autoHeight: true,
                    border: false,
                    items: [
                        new Ext.form.TextField({
                            id: "doligoKeyId",
                            fieldLabel: "Key",
                            name: "doligoKey",
                            value: doligoHash.name,
                            width: 500,
                            readOnly: true,
                            allowBlank: false,
                            listeners: {
                                render: function(c) {
                                    Ext.QuickTips.register({
                                        target: c,
                                        title: '',
                                        text: 'System generated unique identifier'
                                    });
                                }
                            }
                        }),
                        new Ext.form.TextField({
                            id: "doligoNameId",
                            fieldLabel: "Name_Position",
                            name: "doligoName",
                            value: doligoHash.oligoName,
                            width: 500,
                            allowBlank: false,
                            listeners: {
                                render: function(c) {
                                    Ext.QuickTips.register({
                                        target: c,
                                        title: '',
                                        text: 'Describe gene alias name and relative position of the primer within the gene (ex:A, B, C or D)'
                                    });
                                },
                                change: function(t, n) {
                                    var yname = Ext.getCmp("doligoYNameId").getValue();
                                    var npsplitted = n.split("_");
                                    if (yname != null && yname.length > 1 && npsplitted[1].length == 1) {
                                        resolveBandSizeAndSequence(yname, npsplitted[1].toLowerCase());
                                    }
                                }
                            }
                        }),
                        new Ext.form.TextField({
                            id: "doligoYNameId",
                            fieldLabel: "Y Name " + yrefreshLink,
                            name: "doligoYName",
                            value: doligoHash.yName,
                            width: 500,
                            allowBlank: true,
                            listeners: {
                                render: function(c) {
                                    Ext.QuickTips.register({
                                        target: c,
                                        title: '',
                                        text: 'Systematic gene name, required for looking up band sizes and sequences'
                                    });
                                },
                                change: function(t, n) {
                                    var nameposition = Ext.getCmp("doligoNameId").getValue();
                                    var npsplitted = nameposition.split("_");
                                    if (npsplitted.length == 2) {
                                        var position = npsplitted[1];
                                        if (position.length != 1) {
                                            Ext.Msg.alert("Primer Position must be A, B, C, or D");
                                        } else {
                                            resolveBandSizeAndSequence(n, position.toLowerCase());
                                        }
                                    } else {
                                        Ext.Msg.alert("Oligo Name_Position is required and must be in form of GENE_X, where X is A, B, C, or D");
                                    }
                                }
                            }
                        }),
                        new Ext.form.TextField({
                            id: "doligoNotesId",
                            fieldLabel: "Band Sizes",
                            value: doligoHash.notes,
                            width: 500,
                            allowBlank: true,
                            listeners: {
                                render: function(c) {
                                    Ext.QuickTips.register({
                                        target: c,
                                        title: '',
                                        text: 'PCR sizes in the following order: A_D_deletion, A_KanB_deletion, <br>D_KanC_deletion, A_D_wildtype, A_B_wildtype, C_D_wildtype'
                                    });
                                }
                            }
                        }),
                        new Ext.form.TextField({
                            id: "doligoSequenceId",
                            fieldLabel: "Sequence",
                            name: "doligoSequence",
                            value: doligoHash.sequence,
                            width: 500,
                            allowBlank: true,
                            listeners: {
                                render: function(c) {
                                    Ext.QuickTips.register({
                                        target: c,
                                        title: '',
                                        text: 'sequence of the oligo 5� to 3�'
                                    });
                                }
                            }
                        }),
                        new Ext.form.TextField({
                            id: "doligoGeneId",
                            fieldLabel: "Gene",
                            name: "doligoGene",
                            value: doligoHash.gene,
                            width: 500,
                            allowBlank: false,
                            listeners: {
                                render: function(c) {
                                    Ext.QuickTips.register({
                                        target: c,
                                        title: '',
                                        text: 'Gene alias'
                                    });
                                }
                            }
                        }),
                        new Ext.form.TextField({
                            id: "doligoProjectId",
                            fieldLabel: "Project",
                            name: "doligoProject",
                            value: doligoHash.project,
                            width: 500,
                            allowBlank: true,
                            listeners: {
                                render: function(c) {
                                    Ext.QuickTips.register({
                                        target: c,
                                        title: '',
                                        text: 'Yeast Deletion Collection confirmation'
                                    });
                                }
                            }
                        }),
                        new Ext.form.TextField({
                            id: "doligoModificationId",
                            fieldLabel: "Modification",
                            name: "doligoModification",
                            value: doligoHash.modification,
                            width: 500,
                            allowBlank: true,
                            listeners: {
                                render: function(c) {
                                    Ext.QuickTips.register({
                                        target: c,
                                        title: '',
                                        text: 'Indicate any non nucleotide changes (ex: biotin,fluorophore, modified base �)'
                                    });
                                }
                            }
                        }),
                        new Ext.form.TextField({
                            id: "doligoPurificationId",
                            fieldLabel: "Purification",
                            name: "doligoPurification",
                            value: doligoHash.purification,
                            width: 500,
                            allowBlank: true,
                            listeners: {
                                render: function(c) {
                                    Ext.QuickTips.register({
                                        target: c,
                                        title: '',
                                        text: 'Specify purification method of oligo synthesis (ex: Desalt, HPLC, PAGE �)'
                                    });
                                }
                            }
                        }),
                        new Ext.form.TextField({
                            id: "doligoConcentrationId",
                            fieldLabel: "Concentration",
                            name: "doligoConcentration",
                            value: doligoHash.concentration,
                            width: 500,
                            allowBlank: false,
                            listeners: {
                                render: function(c) {
                                    Ext.QuickTips.register({
                                        target: c,
                                        title: '',
                                        text: 'Indicate the concentration and solvent of the stock solution '
                                    });
                                }
                            }
                        }),new Ext.form.TextField({
                            id: "doligoCommentsId",
                            fieldLabel: "Comments",
                            value: doligoHash.comments,
                            width: 500,
                            allowBlank: true,
                            listeners: {
                                render: function(c) {
                                    Ext.QuickTips.register({
                                        target: c,
                                        title: '',
                                        text: 'Deletion Oligo Comments'
                                    });
                                }
                            }
                        }),
                        /*new Ext.Slider({
                         fieldLabel: 'Importance',
                         id: 'imp_slider',
                         isFormField: true,
                         width: 300,
                         increment: 5,
                         minValue: 1,
                         maxValue: 300,
                         plugins: new Ext.ux.SliderTip(),
                         listeners: {
                         dragend:
                         function() {
                         //Ext.getCmp("ciId").setValue(this.getValue());
                         },
                         change:
                         function() {
                         //Ext.getCmp("ciId").setValue(this.getValue());
                         }
                         }
                         }),*/
                        label_title, label_top, label_image, label_bottom
                    ]
                })
            ]
        });
        callback();

    }

    function doSearch() {
        renderDOSearchResult();
    }

    // render the grid to the specified div in the page
    function renderDOSearchResult() {
        var searchResultsButton = Ext.getCmp("showDOSearchResultsId");
        if (myDOData.length == 1) {
            renderDoligoDetails(null);
            return;
        }

        if (searchResultsButton != null || searchResultsButton != undefined) {
            searchResultsButton.disable();
        }
        var mytbar = [
            {
                id: 'do2CSVId',
                text: 'Export2CSV',
                icon: "images/check-green.png",
                cls:'x-btn-text-icon',
                tooltip: 'Export search results to csv',
                listeners: {click:
                        function() {
                            Dudley.lims.DeletionOligo.toCSV();
                        }
                }
            }
        ];
        pagingBar = new Ext.PagingToolbar({
            pageSize: 10,
            store: doligoStore,
            displayInfo: true,
            displayMsg: 'Displaying strains {0} - {1} of {2}',
            emptyMsg: "No strains to display"
        });
        var searchResultsGrid = new Ext.grid.GridPanel({
            id: "doligoSearchResultsId",
            store: doligoStore,
            columns: getOligoSearchColumnHeaders(),
            stripeRows: true,
            //autoExpandColumn: 'DOkey',
            autoHeight: true,
            width: 800,
            title: 'Deletion Oligo',
            renderTo: "sample-search-result-list",
            bbar: pagingBar,
            tbar: mytbar            
        });
        searchResultsGrid.on("celldblclick", function (g, ri, ci, e) {
            renderDoligoDetails(g);
        });
        searchResultsGrid.on("rowcontextmenu", onMessageContextMenu);
    }

    function onMessageContextMenu(grid, rowIndex, e) {
        var activePage = Math.ceil((pagingBar.cursor + pagingBar.pageSize) / pagingBar.pageSize);
        var realIndex = (activePage - 1) * pagingBar.pageSize + rowIndex;
        sptlght.utils.SpotlightUtils.setSelectedRecord(doligoStore.allData.items[realIndex].json);
        sptlght.utils.SpotlightUtils.setSource("do");
        e.preventDefault();
        e.stopEvent();
        var coords = e.getXY();
        spotlightMenu.showAt([coords[0], coords[1]]);
    }

    function loadPrimer(primerType) {
        var myArray = doligoHash.oligoName.split("_");
        var genePrimer = myArray[0] + "_" + primerType;        
        /*var searchOligoUrl = "/addama-rest/dudley-sample/path/datasource/DO/search?MATCHING_ALL_TERMS=true" +
                             "&PROJECTION=oligoName" +
                             "&PROJECTION=notes" +
                             "&PROJECTION=gene" +
                             "&PROJECTION=sequence" +
                             "&PROJECTION=yName" +
                             "&PROJECTION=project" +
                             "&PROJECTION=modification" +
                             "&PROJECTION=purification" +
                             "&PROJECTION=concentration" +
                             "&PROJECTION=orderedBy" +
                             "&oligoName=" + genePrimer;*/
        
        Ext.Ajax.request({
            url: getSolrDOligoUrl("doligoName:" + genePrimer, 1),
            method: "GET",
            success: function(response) {
                var searchResultObj = Ext.util.JSON.decode(response.responseText);
                myDOData = [];
                loadDOSearchResult(0, searchResultObj.response, function() {
                        Ext.getDom("sample-search-result-list").innerHTML = "";
                        Ext.getDom("yo-form").innerHTML = "";
                        renderDOSearchResult();
                });
            },
            failure: function() {
                Ext.Msg.alert("Info", "Primer " + genePrimer + " does not exist");
            }
        });
    }

    function renderDoligoDetails(g) {
        var searchResultsButton = Ext.getCmp("showDOSearchResultsId");
        searchResultsButton.enable();
        doligoHash = new Object();
        if (g != null) {
            populateOligoJson(doligoHash, g);
        } else {
            populateSingleDeletionOligoViaSearch(doligoHash, myDOData[0]);
        }
        loadCreateDOStrain(doligoHash, function() {
            doligoFormRender();
        });
    }

    function doligoFormRender() {
        Dudley.lims.samplemgr.getHousingPanel().activate(doligoPanel);
        Ext.getDom("sample-search-result-list").innerHTML = "";
        Ext.getDom("yo-form").innerHTML = "";
        doligoForm.render("yo-form");
    }
    
    function setDoligoAdmin(jsonObj){
    	limsadmin_obj =  jsonObj;
    	doligoCount = jsonObj.limsadminDOligoCount;
                        doligoMaxNum = jsonObj.limsadminDOligoMaxNum;                       
                        doligoHash = null;
                        Ext.getCmp("showDOSearchResultsId").enable();
                        loadCreateDOStrain(doligoHash, function() {
                            Ext.getDom("sample-search-result-list").innerHTML = "";
                            Ext.getDom("yo-form").innerHTML = "";
                            doligoForm.render("yo-form");
                        });
     }                   

    // public
    return {
        initDO: function(failedCB) {
            //perl GET.pl http://ravioli-2:8080/addama-rest/dudley-sample/path/datasource/DO/search?FREE_TEXT='*'&PROJECTION='matingType'&PROJECTION='alias'&PROJECTION='genotype'
            initDOStore(failedCB, function() {
                eventManager.fireStatusMessageEvent({ text: "Finishing init DOStore", level: "info" });
            });
        },
        setDOLoaded: function(boo) {
            doligoLoaded = boo;
        },

        getDOPanel: function() {
            loadDOPanel();
            return doligoPanel;
        },

        viewPrimer: function(primerType) {
            Ext.getDom("sample-search-result-list").innerHTML = "";
            Ext.getDom("yo-form").innerHTML = "";
            loadPrimer(primerType);
        },
        getDOStore: function() {
            return doligoStore;
        },

        loadNewDO: function() {
            Ext.getDom("yo-form").innerHTML = "";
            
            getSolrLimsAdmin(setDoligoAdmin); 
        },
        loadSearchResult: function() {
            Ext.getDom("sample-search-result-list").innerHTML = "";
            renderDOSearchResult();
        },
        setSearchParams: function(myParam, myOption) {
            searchInput = myParam;
            searchOption = myOption;
        },
        selectYGene: function(sequence, bandsizes) {
            updateYGeneLookup(sequence, bandsizes);
        },
        refreshYGene: function() {
            doYGeneRefresh();
        },
        toCSV: function() {
            exportOligos(myDOData, "doligo");
        },
        setArrayData: function(data) {
                    myDOData = data;
         }
    };
}
        ();
